package top.i51213.fastaction.printer;

import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.printservice.PrintDocument;
import android.printservice.PrintJob;
import android.printservice.PrintService;
import android.printservice.PrinterDiscoverySession;

import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import top.i51213.fastaction.BuildConfig;
import top.i51213.fastaction.ReceiveActivity;
import top.i51213.fastaction.ReceiveClassName;
import top.i51213.fastaction.uri.MimeType;
import top.i51213.fastaction.uri.UriWriter;
import top.i51213.fastaction.util.IOUtil;

public class SharePrintService extends PrintService {
    @Nullable
    @Override
    protected PrinterDiscoverySession onCreatePrinterDiscoverySession() {
        return new MyPrinterDiscoverySession(this);
    }

    @Override
    protected void onRequestCancelPrintJob(PrintJob printJob) {
        printJob.cancel();
    }

    @Override
    protected void onPrintJobQueued(PrintJob printJob) {
        if (!printJob.isQueued()) {
            printJob.fail("打印机未就绪!");
            return;
        }
        try {
            printJob.start();

            PrintDocument printdocument = printJob.getDocument();
            InputStream fis = new BufferedInputStream(new ParcelFileDescriptor.AutoCloseInputStream(printdocument.getData()));

            String filename = IOUtil.getFileNameNoExt(printdocument.getInfo().getName()) + ".pdf";
            UriWriter uriWriter = new UriWriter(this, filename, MimeType.Application.Pdf, true);
            IOUtil.copyToAndClose(fis, uriWriter.openOutputStream());
            Uri uri = filterUri(uriWriter.getUri());
            //ArrayList<Uri> uris=new ArrayList<>(Collections.singletonList(uriWriter.getUri()));
            //ReceiveActivity.startThis(this.getApplicationContext(), ReceiveClassName.PdfShare,uris,MimeType.Application.Pdf.get());
            ReceiveActivity.startThis(this.getApplicationContext(), uri, MimeType.Application.Pdf.get());
            try{
                Thread.sleep(500);
            }catch (Exception ignored){

            }
            printJob.complete();
        } catch (Exception ignored) {
            printJob.fail("发生异常:" + ignored.getMessage());
            printJob.cancel();
        }
    }

    private Uri filterUri(Uri uri) {
        if ("file".equals(uri.getScheme())) {
            File file = new File(uri.getPath());
            uri = FileProvider.getUriForFile(this.getApplicationContext(), BuildConfig.APPLICATION_ID + ".provider", file, file.getName());
        }
        return uri;
    }
}
